package com.anan.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.anan.pojo.dto.OssPolicyResult;
import com.anan.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class OssServiceImpl implements OssService {

    @Value("${aliyun.oss.endpoint}")
    private String ALIYUN_OSS_ENDPOINT;
    @Value("${aliyun.oss.bucketName}")
    private String ALIYUN_OSS_BUCKET_NAME;
    @Value("${aliyun.oss.policy.expire}")
    private long ALIYUN_OSS_POLICY_EXPIRE;
    @Value("${aliyun.oss.maxSize}")
    private long ALIYUN_OSS_MAX_SIZE;
    @Value("${aliyun.oss.dir.prefix}")
    private String ALIYUN_OSS_DIR_PREFIX;
//    @Value("${aliyun.oss.callback}")
//    private String callback;

    @Autowired
    private OSSClient ossClient;

    /**
     * 签名生成
     * @return
     */
    @Override
    public OssPolicyResult policy() {
        OssPolicyResult result = new OssPolicyResult();
        //存储目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dir = ALIYUN_OSS_DIR_PREFIX+sdf.format(new Date());
        //签名有效期
        long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_POLICY_EXPIRE * 100;
        Date expiration = new Date(expireEndTime);
        //文件大小
        long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024;
        //提交节点
        String action = "https://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT;

        try{
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,0,maxSize);
            policyConditions.addConditionItem(MatchMode.StartWith,PolicyConditions.COND_KEY,dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature  = ossClient.calculatePostSignature(postPolicy);
            //返回结果
            result.setAccessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId());
            result.setPolicy(encodedPolicy);
            result.setSignature(postSignature);
            result.setDir(dir);
            result.setHost(action);
        }catch (Exception e){
            log.error("签名生成失败：" + e);
        }
        return result;
    }
}
